﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace GoogleSync
{
    public partial class SyncWindow : Form
    {
        String folderLocation;
        Store store;
        private static String CREDS = ContactSync.HOME + "creds.dat";
        Outlook.Application app;

        public SyncWindow(Outlook.Application myApp)
        {
            app = myApp;
            InitializeComponent();
            retrieveCredentials();
        }

        private void retrieveCredentials()
        {
            if (File.Exists(CREDS))
            {
                FileStream fi = new FileStream(CREDS, FileMode.Open, FileAccess.Read);
                BinaryFormatter bf = new BinaryFormatter();
                store = (Store)bf.Deserialize(fi);
                fi.Close();
            }
            else
            {
                store = new Store();
            }
            folderLocation = store.folderLocation;
            username.Text = store.username;
            password.Text = store.password;
        }

        private void saveCredentials()
        {
            store.folderLocation = folderLocation;
            store.username = username.Text;
            store.password = password.Text;
            FileStream fo = new FileStream(CREDS, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fo, store);
            fo.Flush();
            fo.Close();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            timer1_Tick(null, null);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (username.Text.Length > 0 && password.Text.Length > 0)
            {
                ContactSync.main(app, folderLocation, username.Text, password.Text);
                this.folderLocation = ContactSync.getFolderPath();
                saveCredentials();
            }
        }

        [Serializable]
        private class Store
        {
            public String username = "";
            public String password = "";
            public String folderLocation = null;
        }


        private void SyncWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

    }
}
